<template>
  <div>
    <!-- 报告列表 -->
    <div
      class="w-full flex justify-between text-[0.7rem] bg-[#f7f7f7]"
      :style="{ height: 'calc(100vh - ' + props.heightNum + 'rem)' }"
    >
      <el-scrollbar class="w-[28%]" style="height: calc(100vh - 10rem)">
        <el-card
          v-for="item in templateList"
          :key="item.id"
          @click="viewReport(item)"
          :class="{
            pdf_active: currentForm.id == item.id,
          }"
          class="card_item mb-1"
        >
          {{ item.templateName }}
        </el-card>
      </el-scrollbar>
      <el-card class="w-[71%]">
        <embed
          :src="reportPdf"
          type="application/pdf"
          width="100%"
          :style="{
            height: 'calc(100vh - 1.2rem - ' + props.heightNum + 'rem)',
          }"
        />
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from "vue";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import { useUserStore } from "@/pinia";
import { storeToRefs } from "pinia";
import { watchStorage, setStorageWithEvent } from "@/utils/GlobalMonitoring.js";

import { handleApiResponse } from "@/utils/request.js";
import {
  ListTemplateInfos,
  CreateReportInfo,
  QueryRegion,
} from "../../../../../../wailsjs/go/api/ReportApi.js";

onMounted(async () => {
  await getResultInfo();
});

const props = defineProps({
  heightNum: {
    type: Number,
    default: 10,
  },
  checkId: {
    type: Number,
    default: -1,
  },
  detailForm: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const userStore = useUserStore();
const { checkDetailForm, device_info } = storeToRefs(userStore);

const templateList = ref([]);
async function getTemplateList() {
  handleApiResponse(() => ListTemplateInfos({ page: 1, size: 1234 })).then(
    (res) => {
      if (res.code == 0) {
        templateList.value = res.data.list || [];
        templateList.value = templateList.value.filter(
          (item) => item.status == 1
        );
        templateList.value.forEach((item) => {
          item.region = JSON.parse(item.region || "[]");
        });
        if (templateList.value?.length > 0) {
          viewReport(templateList.value[0]);
        }
      }
    }
  );
}

const resultInfo = ref(""); // 数据分析结果
const regionData = ref([]);
async function getResultInfo() {
  let projectIds =
    props.checkId == -1
      ? checkDetailForm.value.projectList.map((item) => item.id)
      : props.detailForm.projectList.map((item) => item.id);

  handleApiResponse(() =>
    QueryRegion({
      checklistId:
        props.checkId == -1 ? checkDetailForm.value.id : props.checkId,
      projectIds: projectIds,
    })
  ).then((res) => {
    if (res.code == 0) {
      resultInfo.value = res.data.aiResult
        ? res.data.aiResult
        : res.data.editResult
        ? res.data.editResult
        : device_info.value;

      regionData.value = res.data.regionInfos || [];
      regionData.value =
        res.data.regionInfos.map((item) => {
          return {
            regionId: item.regionId,
            regionName: item.regionName,
            projectId: item.projectId,
            regionResult: JSON.parse(item.regionResult || "[]"),
          };
        }) || [];

      getTemplateList();
    }
  });
}

// 当前正在点击的表单
const currentForm = ref({});
const reportPdf = ref(""); // 查看报告
const isClicking = ref(false); // 防止重复点击
async function viewReport(row) {
  if (isClicking.value) return; // 如果正在点击，直接返回
  isClicking.value = true;
  setTimeout(() => {
    isClicking.value = false;
  }, 2000);

  const loading = ElLoading.service({
    lock: true,
    text: `正在生成${row.templateName}中,请稍后...`,
    background: "rgba(0, 0, 0, 0.7)",
  });

  currentForm.value = row;
  reportPdf.value = "";

  let dataListInfo = ""; // '[][][]'
  let resultData = ""; // 'a=1&&b=2'

  row.region.forEach((e) => {
    regionData.value.forEach((item) => {
      if (e == item.regionId) {
        if (dataListInfo) {
          dataListInfo += "&&" + JSON.stringify(item.regionResult);
        } else {
          dataListInfo = JSON.stringify(item.regionResult);
        }
        item.regionResult.forEach((val) => {
          if (resultData) {
            resultData += "&&" + val.datapointTypeValue + "=" + val.value;
          } else {
            resultData = val.datapointTypeValue + "=" + val.value;
          }
        });
      }
    });
  });

  //   console.log({
  //     customId: checkDetailForm.value.customerId,
  //     customRelativeId: checkDetailForm.value.relationId,
  //     age: checkDetailForm.value.age,
  //     sex: checkDetailForm.value.sex,
  //     listId: checkDetailForm.value.id,
  //     name: checkDetailForm.value.relationName,
  //     phone: checkDetailForm.value.phone,
  //     templateId: row.id,
  //     resultInfo: resultInfo.value,
  //     dataListInfo: dataListInfo,
  //     resultData: resultData,
  //   });
  //   return;

  handleApiResponse(() =>
    CreateReportInfo({
      customId:
        props.checkId == -1
          ? checkDetailForm.value.customerId
          : props.detailForm.customerId,
      customRelativeId:
        props.checkId == -1
          ? checkDetailForm.value.relationId
          : props.detailForm.relationId,
      age:
        props.checkId == -1 ? checkDetailForm.value.age : props.detailForm.age,
      sex:
        props.checkId == -1 ? checkDetailForm.value.sex : props.detailForm.sex,
      listId:
        props.checkId == -1 ? checkDetailForm.value.id : props.detailForm.id,
      name:
        props.checkId == -1
          ? checkDetailForm.value.relationName
          : props.detailForm.relationName,
      phone:
        props.checkId == -1
          ? checkDetailForm.value.phone
          : props.detailForm.phone,
      templateId: row.id,
      resultInfo: resultInfo.value,
      dataListInfo: dataListInfo,
      resultData: resultData,
      templateApi: row.templateApi,
    })
  )
    .then((res) => {
      if (res.code == 0) {
        reportPdf.value = res.data.reportPdf || "";
      }
    })
    .finally(() => {
      loading.close();
    });
}
</script>

<style scoped lang="scss">
.card_item:deep(.el-card__body) {
  @apply w-full h-[2.5rem]  flex justify-center items-center overflow-hidden;

  &:hover {
    @apply bg-[var(--theme-color)] cursor-pointer text-[white];
  }
  //   background: #000;;
}
.pdf_active:deep(.el-card__body) {
  background-color: var(--theme-color) !important;
  color: white !important;
}
</style>